package com.lvfuyang.commonproject.controller;

import com.alibaba.fastjson.JSONObject;
import com.lvfuyang.commonproject.common.Result;
import com.lvfuyang.commonproject.dto.LoginRequest;
import com.lvfuyang.commonproject.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest request) {
        Map<String, Object> result = authService.login(request);

        log.info("用户登录成功，用户ID：{}", result.get("userId"));
        return Result.success("登录成功", result);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Map<String, Object>> logout(@RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        authService.logout(token);
        log.info("用户登出成功，用户token：{}", token);
        return Result.success("登出成功", new HashMap<>());
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public Result<Map<String, Object>> refresh(@RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        String newToken = authService.refreshToken(token);

        Map<String, Object> result = new HashMap<>();
        result.put("token", newToken);

        log.info("用户Token刷新成功，用户ID：{}", authService.getUserByToken(newToken).getUuid());

        return Result.success("Token刷新成功", result);
    }


} 